/**
 * @file verReceta.java
 * @brief Interfaz que muestra las recetas previas (historial) de un paciente.
 *
 * Copyright (C)  - May [2011]
 *
 * @author Miguel Ángel Díaz López
 * @version 01.00
 *
 * @footnote e-mail:  admin    at etsiit.es
 */

package interfaces;


import Controlador.*;
import GestorCitas.*;
import GestorUsuarios.Medico;
import GestorUsuarios.Usuario;
import java.awt.event.*;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.jdesktop.application.Action;
import paciente.Interfaces;
import paciente.Interfaz;
import paciente.PacienteView;

/**
 *
 * @author frpp
 */
public class verReceta extends javax.swing.JPanel{

    private TableModel _modelo;
    private PacienteView _app;
    private Receta[]  _receta ;
    private LineaReceta[][]  _l_receta = null;
    Interfaces _anterior;

    /** Creates new customizer NewCustomizer */
    public verReceta(PacienteView a) {
        _app = a;
        initComponents();

        panel_recetas.setRowHeight(32);
        panel_recetas.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    }

    public void rellenaDatos(Integer id_paciente, Interfaces ant) throws SQLException, IOException, ClassNotFoundException, SQLException, NoSuchAlgorithmException, ParseException {
        DateFormat fecha_formato = new SimpleDateFormat("dd/MM/yyyy");
        int menor;
        _anterior = ant;

        // Limpiamos campos + tabla
        Interfaz.limpiarTabla(panel_recetas);
        nomusu.setText("");

        // Obtenemos todas las recetas (historial) para el paciente
        _receta = Controlador.obtenerRecetas(id_paciente);
        if(_receta == null) {
            _app.abrirMensajeError("No se encontró ninguna cita previa para dicho paciente.", _anterior);
            return;
        }

        // Listamos todas las lineas recetas PARA CADA RECETA!
        _l_receta = new LineaReceta[_receta.length][];
        for(int i = 0; i < _receta.length; i++) {
           _l_receta[i] = LineaReceta.get(_receta[i].getIdReceta(), null, null, null, null, null, false, null);
        }

        // Rellenamos la tabla
        String Linea_Receta = null;
        String[] columnNames = {"Medico","Fecha","Líneas de receta"};
        Object[][] data =  new Object[_l_receta.length][];
        //Guardamos en data[][] todas la lista de recetas.
        for(int i=0;i<_l_receta.length;i++) {
           Medico m = (Medico) Usuario.get(_l_receta[i][0].getCita().getIdMedico());
           Linea_Receta = "";
           data[i] = new Object[3];
           data[i][0] = m.getNombre()+" "+m.getApellidos();
           data[i][1] = fecha_formato.format(_l_receta[i][0].getFechaInicio());
           for(int z = 0 ; z < _l_receta[i].length; z++){
              Linea_Receta += _l_receta[i][z].getIdLinea();
              if(z !=( _l_receta[i].length-1)) Linea_Receta += ", ";
           }
           data[i][2] = Linea_Receta;
        }

        //Ahora los ordenamos por fecha.
        Object[][] data2 =  new Object[_l_receta.length][];
        for(int j=0; j < _l_receta.length;j++){
            data2[j] = new Object[3]; // Estructura auxiliar
            menor = j;
            for(int z=j+1; z < _l_receta.length;z++){
                if( _l_receta[menor][0].getFechaInicio().after(_l_receta[z][0].getFechaInicio()))// si algo es mayor igual  que otro. los intercambiamos
                        menor = z;                  
            }
            if(j+1 < _l_receta.length){ // se modificó 'z'
                data2[0][0] = data[j][0];
                data2[0][1] = data[j][1];
                data2[0][2] = data[j][2];

                data[j][0] = data[menor][0];
                data[j][1] = data[menor][1];
                data[j][2] = data[menor][2];

                data[menor][0] = data2[0][0];
                data[menor][1] = data2[0][1];
                data[menor][2] = data2[0][2];
            }
        }


        _modelo = new DefaultTableModel(data, columnNames);
        panel_recetas.setModel(_modelo);

        // Cargamos los eventos para el ratón
        panel_recetas.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int fila = panel_recetas.getSelectedRow();
                if(fila >= 0) nomusu.setText(_l_receta[fila][0].getObservaciones());
            }
        });
    }



    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        panel_recetas = new javax.swing.JTable();
        jButton3 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        nomusu = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();

        setMaximumSize(new java.awt.Dimension(780, 470));
        setMinimumSize(new java.awt.Dimension(780, 470));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Entrega", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, Interfaz.setFontSize()));
        jPanel1.setMaximumSize(new java.awt.Dimension(780, 470));
        jPanel1.setName("jPanel1"); // NOI18N

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)), "Información de recetas", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, Interfaz.setFontSize()));
        jPanel5.setName("jPanel5"); // NOI18N

        jScrollPane1.setFont(new java.awt.Font("Lucida Grande", 0, 18));
        jScrollPane1.setName("jScrollPane1"); // NOI18N

        panel_recetas.setFont(new java.awt.Font("Tahoma", 0, 18));
        panel_recetas.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Médico", "Fecha", "Líneas receta"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        panel_recetas.setName("panel_recetas"); // NOI18N
        jScrollPane1.setViewportView(panel_recetas);

        org.jdesktop.layout.GroupLayout jPanel5Layout = new org.jdesktop.layout.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 722, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE)
        );

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(paciente.PacienteApp.class).getContext().getActionMap(verReceta.class, this);
        jButton3.setAction(actionMap.get("informacion")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(paciente.PacienteApp.class).getContext().getResourceMap(verReceta.class);
        jButton3.setIcon(resourceMap.getIcon("jButton3.icon")); // NOI18N
        jButton3.setLabel(resourceMap.getString("jButton3.label")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N

        jLabel1.setFont(Interfaz.setFontSize());
        jLabel1.setText("Observaciones");
        jLabel1.setName("jLabel1"); // NOI18N

        nomusu.setEditable(false);
        nomusu.setFont(new java.awt.Font("Lucida Grande 18 12 18", 0, 18));
        nomusu.setName("nomusu"); // NOI18N

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                        .add(nomusu, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 658, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButton3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 110, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(17, 17, 17))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                        .add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE)
                        .add(631, 631, 631))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                        .add(jPanel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                .add(jPanel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(nomusu, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE)
                    .add(jButton3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 88, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jButton2.setAction(actionMap.get("aceptar")); // NOI18N
        jButton2.setIcon(resourceMap.getIcon("jButton2.icon")); // NOI18N
        jButton2.setLabel(resourceMap.getString("jButton3.label")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jButton2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 84, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jButton2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 76, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jPanel1.getAccessibleContext().setAccessibleName("");
    }// </editor-fold>//GEN-END:initComponents





    @Action
    public void aceptar() throws NoSuchAlgorithmException, IOException, ClassNotFoundException, SQLException {
        _app.volver(_anterior);
    }

    @Action
    public void informacion() throws SQLException, IOException, ClassNotFoundException, NoSuchAlgorithmException, ParseException{// si informacion=AYUDA..porque repetimos el boton??????No te resulta estraño'????
        int fila = panel_recetas.getSelectedRow();
        if(fila >= 0){
            Receta recetilla = _l_receta[fila][0].getReceta();
            _app.abrirVerRecetasDetallado(recetilla, _anterior);
        }
    }




    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField nomusu;
    private javax.swing.JTable panel_recetas;
    // End of variables declaration//GEN-END:variables


}
